﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SCTO.Center.Controllers
{
    [ApiController]
    [Route("scto")]
    public class SctoController : Controller
    {
        [HttpPost("register")]
        public IActionResult Register([FromForm]string clientId, [FromForm]string pubKey)
        {
            SCTOService.PublicKeyDic.Add(clientId, pubKey);
            return Ok();
        }

        [HttpPost("upload")]
        public IActionResult Upload([FromForm]string clientId, [FromForm] string fileName, [FromForm] string fileSignature)
        {
            var file = new SctoFileInfo { FileName = fileName, Signature = fileSignature };
            if (!SCTOService.Files.ContainsKey(file))
                SCTOService.Files.Add(file, new List<string> { clientId });
            else
                SCTOService.Files[file].Add(clientId);
            return Ok();
        }

        [HttpGet("file")]
        public IActionResult GetFile(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                return new JsonResult(SCTOService.Files.Keys.ToArray());
            else
                return new JsonResult(from client in SCTOService.Files[new SctoFileInfo { FileName = fileName }]
                                      select new
                                      {
                                          Client = client,
                                          PublicKey = SCTOService.PublicKeyDic[client]
                                      });
        }
    }
}
